package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.PageDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**

 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        //先查询中间表根据分类id，获取到分类品牌的中间对象的集合，取出品牌id集合，根据品牌id集合查询对应的品牌集合
        List<Long> brandIds = this.categoryBrandService
                .query()
                .eq("category_id", id)
                .list()
                .stream()
                .map(CategoryBrand::getBrandId)
                .collect(Collectors.toList());
        return BrandDTO.convertEntityList(listByIds(brandIds));
    }


    @Override
    public PageDTO<BrandDTO> queryBrandByPage(Integer page, Integer rows, String key) {
        // 1.分页信息的健壮性处理
        page = Math.min(page, 100);
        rows = Math.max(rows, 5);

        //2分页
        Page<Brand> pages = new Page<>(page, rows);

        //3判断key是否存在
        boolean isKeyExists = StringUtils.isNoneBlank(key);

        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(pages);

        // 5.封装结果
        List<Brand> list = pages.getRecords();
        return new PageDTO<>(pages.getTotal(), pages.getPages(), BrandDTO.convertEntityList(list));
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存brand
        this.save(brand);
        //封装中间表对象的集合
        List<CategoryBrand> list = brandDTO.getCategoryIds()
                .stream().map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        categoryBrandService.saveBatch(list);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        //1.更新品牌
        boolean success = updateById(brandDTO.toEntity(Brand.class));
        if (!success) {
            //更新失败
            throw new LyException(500, "更新品牌失败!");
        }
        //2.根据品牌id删除中间表数据
        success = categoryBrandService.remove(new QueryWrapper<CategoryBrand>()
                .eq("brand_id", brandDTO.getId())
        );
        if (!success) {
            //更新失败，抛出异常
            throw new LyException(500, "删除中间表数据失败");
        }
        //3.重新插入中间表数据
        List<CategoryBrand> list = brandDTO.getCategoryIds()
                .stream()
                .map(id -> CategoryBrand.of(id, brandDTO.getId()))
                .collect(Collectors.toList());
        //4.写入中间表数据
        categoryBrandService.saveBatch(list);
    }
}
